package com.poker.controller;

import com.poker.consts.Consts;
import com.poker.entity.ManagerInfo;
import com.poker.entity.ManagerMenu;
import com.poker.service.ManagerMenuService;
import com.poker.shiro.ManagerToken;
import com.poker.util.Misc;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.UnauthorizedException;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.*;

@Controller
public class HomeController extends BaseController {

    @Resource
    private ManagerMenuService managerMenuService;

    @RequestMapping("/403")
    public String unauthorizedRole(){
        return "manager/403";
    }

    @RequestMapping({"/login", "/"})
    public String login (Model model, ManagerInfo manager) {
        String username = manager.getUserName();
        String password = manager.getPassWord();

        ManagerInfo sessionManager = (ManagerInfo) getObjectFromShiroSession(Consts.Session.MANAGER);

        if (Misc.isNotEmpty(sessionManager)) return redirect("doLogin");

        if(Misc.isEmpty(username) || Misc.isEmpty(password)) {
            model.addAttribute("manager", new ManagerInfo());
            return managerPage("login");
        }

        String msg = null;
        Subject currentSubject = SecurityUtils.getSubject();

        try {
            currentSubject.login(new ManagerToken(username, password));
        } catch (IncorrectCredentialsException e) {
            msg = "登录密码错误";
        } catch (ExcessiveAttemptsException e) {
            msg = "登录失败次数过多";
        } catch (LockedAccountException e) {
            msg = "帐号已被锁定";
        } catch (DisabledAccountException e) {
            msg = "帐号已被禁用";
        } catch (ExpiredCredentialsException e) {
            msg = "帐号已过期";
        } catch (UnknownAccountException e) {
            msg = "帐号不存在";
        } catch (UnauthorizedException e) {
            msg = "您没有得到相应的授权！";
        } catch (AuthenticationException e) {
            msg = "账号信息为空";
        } catch (Exception e) {
            msg = "系统异常";
        }

        if (currentSubject.isAuthenticated()) return redirect("doLogin");

        model.addAttribute("msg", msg);
        model.addAttribute("manager", new ManagerInfo());
        return managerPage("login");
    }

    @RequestMapping("/doLogin")
    public String doLogin(Model model) {
        model.addAttribute("nickName", getStringFromShiroSession(Consts.Session.MANAGER_NICK_NAME));
        return managerPage("home");
    }

    @ResponseBody
    @RequestMapping("/getMenus")
    public String getMenus() {
        List<ManagerMenu> supMenuList = (List<ManagerMenu>) getObjectFromShiroSession(Consts.Session.MANAGER_MENUS);

        if (Misc.isNotEmpty(supMenuList) && supMenuList.size() > 0)
            return toJson(true, null, supMenuList);

        ManagerInfo managerInfo = loginManager();
        List<ManagerMenu> menus = managerMenuService.findMenus(managerInfo.getMenus());

        // 存储父菜单:键-->菜单id,值-->菜单
        Map<String, ManagerMenu> supMenuMap = new HashMap<>();
        // 存储父菜单
        supMenuList = new ArrayList<>();
        // 存放菜单url链接
        Set<String> linkSet = new HashSet<>();

        if (Misc.isNotEmpty(menus) && menus.size() > 0) {
            for (ManagerMenu menu: menus) {
                if (Misc.isEmpty(menu.getPid())) {
                    supMenuMap.put(menu.getId(), menu);
                    supMenuList.add(menu);
                }
            }

            ManagerMenu parentMenu;
            for (ManagerMenu menu: menus) {
                parentMenu = null;
                if (Misc.isNotEmpty(menu.getPid())) {
                    linkSet.add(menu.getLink());
                    parentMenu = supMenuMap.get(menu.getPid());
                }

                if (null != parentMenu) parentMenu.addSubMenu(menu);
            }

        }

        getShiroSession().setAttribute(Consts.Session.MANAGER_MENUS, supMenuList);
        return toJson(true, null, supMenuList);
    }

}
